package com.mlnx.utils;

import java.io.IOException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * @author zzb
 * @create 2019/12/2 15:13
 */
public class MD5Util {
    protected static char[] hexDigits = { '0', '1', '2', '3', '4', '5', '6',
            '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
    protected static MessageDigest messageDigest = null;
    static {
        try {
            messageDigest = MessageDigest.getInstance("MD5");
        } catch(NoSuchAlgorithmException nsaex) {
            System.err.println(MD5Util.class.getName()
                    + "初始化失败，MessageDigest不支持MD5Util。");
            nsaex.printStackTrace();

        }
    }

    /**
     * 获取字符串的MD5
     * @param input
     * @return
     */
    public static String getStringMD5(String input){
        try {
            // get MD5 digest
            MessageDigest mDigest = MessageDigest.getInstance("MD5");
            // The input String to Byte Array
            byte[] inputArr = input.getBytes();
            // Updates the digest using the specified byte.
            mDigest.update(inputArr);
            // Completes the hash computation by performing final operations such as padding.
            // The digest is reset after this call is made.
            byte[] resultArr = mDigest.digest();
            //
            return byteArrToHex(resultArr);
        } catch (NoSuchAlgorithmException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return null;
    }

    /**
            * 将字节数组转换为16进制字符串
     * @param
     * @return 16进制字符串
     */
    private static String byteArrToHex(byte[] byteArr) {
        // Initialize the character array, used to store each hexadecimal string
        char[] hexDigits = {'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'};
        // Initialize a char Array, used to form the result string
        char[] resultCharArr = new char[byteArr.length*2];
        // Traverse the byte array, converted into characters in a character array
        int index = 0;
        for (byte b : byteArr) {
            resultCharArr[index++] = hexDigits[b>>> 4 & 0xf];
            resultCharArr[index++] = hexDigits[b & 0xf];
        }
        return new String(resultCharArr);
    }

    public static void main(String[] args) throws IOException {
//        long begin = System.currentTimeMillis();
//        File file = new File("D:/in.txt");
//        String md5 = getFileMD5String(file);
        StringBuilder builder = new StringBuilder();

        String sercet="62CYBlgXtoL9lUCB";
        String num="123";
        String device="358688000033339858";
        builder.append(num).append(device).append(sercet);
        String md5 = getStringMD5(builder.toString());
//        long end = System.currentTimeMillis();
//        System.out.println("md5: " + md5 + ((end - begin) / 1000) + "s");
        System.out.println(md5);
    }

}
